/**
* 基础菜单 用户管理
*/
<template xmlns="http://www.w3.org/1999/html">
  <div class="app-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
  <br>
    <el-row :gutter="20">
      <!--左边部门列表-->
      <el-col :span="3" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            :highlight-current="true"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--右边用户信息-->
      <el-col :span="21" :xs="24">
        <!-- 搜索筛选 -->
        <el-form :inline="true" :model="formInline"   ref="formInline" class="user-search">
          <el-form-item label="搜索：" prop="status">
            <el-select size="small" v-model="formInline.status" placeholder="请选择">
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" value="0"></el-option>
              <el-option label="禁用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="loginName">
            <el-input size="small" v-model="formInline.loginName" placeholder="请输入账号名"  @keyup.enter.native="search"></el-input>
          </el-form-item>
          <el-form-item label="" prop="userName">
            <el-input size="small" v-model="formInline.userName" placeholder="请输入用户名" @keyup.enter.native="search"></el-input>
          </el-form-item>
          <el-form-item label="" prop="mobile">
            <el-input size="small" v-model="formInline.mobile" placeholder="请输入手机号" @keyup.enter.native="search"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button> <el-button size="small" type="primary" icon="el-icon-delete" @click="clearForm">清空</el-button>
          </el-form-item>

        </el-form>
        <el-row size="small">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addUser" v-has="'sys:user:add'" >添加</el-button>
        </el-row>
        <br>

        <!-- 用户列表 -->
        <el-table size="small" @selection-change="selectChange" :data="userData" highlight-current-row v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.1)" border element-loading-text="拼命加载中" style="width: 100%;">
          <el-table-column align="center" type="selection" width="50">

          </el-table-column>
          <el-table-column align="center" sortable prop="loginName" label="账号名" width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="userName" label="用户名" width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="dept.deptName" label="部门名称" width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="mobile" label="手机号" width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="sex" label="性别" min-width="50">
            <template slot-scope="scope">
              <div v-if="scope.row.sex==1">男</div>
              <div v-else-if="scope.row.sex==2">女</div>
              <div v-else="scope.row.sex==3">保密</div>
            </template>
          </el-table-column>
          <el-table-column align="center" sortable prop="email" label="邮件" min-width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="address" label="地址" min-width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="birthday" label="生日" min-width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="idCard" label="身份证" min-width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="createTime" label="创建时间" min-width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="updateTime" label="更新时间" min-width="120">
          </el-table-column>
          <el-table-column align="center" sortable prop="status" label="状态" min-width="50">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status=='0'?nshow:fshow" active-color="#13ce66" inactive-color="#ff4949" @change="editType(scope.$index, scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="300">
            <template slot-scope="scope">
              <el-button size="mini" type="success"  icon="el-icon-edit" @click="editUser(scope.$index, scope.row)" v-has="'sys:user:edit'" >编辑</el-button>
              <el-button size="mini"  type="danger" icon="el-icon-delete"  @click="deleteUser(scope.$index, scope.row)" v-has="'sys:user:delete'" >删除</el-button>
              <el-button size="mini" type="success" icon="el-icon-edit"  @click="resetPassword(scope.$index, scope.row)"  v-has="'sys:user:updatePassWord'" >修改密码</el-button>
            </template>
          </el-table-column>
        </el-table>


        <!-- 分页组件 -->
        <pagination v-bind:child-msg="pageInfo" @callFather="callFather"></pagination>

        <!-- 编辑界面 -->
        <el-dialog :title="title" :visible.sync="userFormVisible" width="30%" @click='closeDialog("edit")'>
          <el-form label-width="80px" ref="userForm" :model="userForm" :rules="userFormRules">
            <el-form-item label="账号名" prop="loginName">
              <el-input size="small" v-model="userForm.loginName" auto-complete="off" placeholder="请输入账号名" :disabled="title=='添加用户'?false:true"></el-input>
            </el-form-item>
            <el-form-item label="归属部门" prop="deptId">
              <tree-select v-model="userForm.deptId" :options="deptOptions" placeholder="请选择归属部门" />
            </el-form-item>
            <el-form-item label="姓名" prop="userName">
              <el-input size="small" v-model="userForm.userName" auto-complete="off" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input size="small" v-model="userForm.mobile" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="邮件" prop="email">
              <el-input size="small" v-model="userForm.email" placeholder="请输入邮箱地址"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input size="small" v-model="userForm.address" placeholder="请输入地址"></el-input>
            </el-form-item>
            <el-form-item label="身份证" prop="idCard">
              <el-input size="small" v-model="userForm.idCard" placeholder="请输身份证"></el-input>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="userForm.birthday" type="date" placeholder="选择出生日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio v-model="userForm.sex" :label="1">男</el-radio>
              <el-radio v-model="userForm.sex" :label="2">女</el-radio>
              <el-radio v-model="userForm.sex" :label="3">保密</el-radio>
            </el-form-item>
            <el-form-item label="岗位">
              <el-select v-model="userForm.postIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色">
              <el-select v-model="userForm.roleIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select size="small" v-model="userForm.status" placeholder="请选择" >
                <el-option label="启用" :value="0"></el-option>
                <el-option label="禁用" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
            <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('userForm')">保存</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  import pagination from '@/components/pagination'
  import TreeSelect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  export default {
    data() {
      return {
        // 请求数据参数
        formInline: {
          page: 1,
          pageSize: 10,
          loginName: '',
          userName: '',
          mobile: '',
          deptId:'',
          status: ''
        },
        // 部门树选项
        deptOptions: undefined,
        // 部门名称
        deptName: undefined,
        // 岗位选项
        postOptions: [],
        // 角色选项
        roleOptions: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        nshow: true, //switch开启
        fshow: false, //switch关闭
        loading: false, //是显示加载
        userFormVisible: false, //控制用户添加页面显示与隐藏
        title: "添加用户",
        userData:[], // 用户列表数据
        selectData: [], // 选择数据
        userForm:{
          userId:'',
          deptId:'',
          loginName:'',
          userName:'',
          status:'',
          sex:'',
          mobile:'',
          email:'',
          address:'',
          birthday:'',
          idCard:'',
          avatar:'',
          postIds:undefined,
          roleIds:undefined
        },
        // 分页参数
        pageInfo: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        // rules表单验证
        userFormRules: {
          userName: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          loginName: [
            { required: true, message: '请输入账号名', trigger: 'blur' }
          ],
          deptId: [
            { required: true, message: "归属部门不能为空", trigger: "blur" }
          ],
          status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {
              pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
              required: true,
              message: '请输入正确的手机号',
              trigger: 'blur'
            }
          ],
          userEmail: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {
              pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
              required: true,
              message: '请输入正确的邮箱',
              trigger: 'blur'
            }
          ],
          sex: [{ required: true, message: '请选择性别', trigger: 'blur' }]
        },
      }
    },
    // 注册组件
    components: {
      pagination,TreeSelect
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      }
    },
    created(){
      this.getDeptTreeList();
      this.getUserList()
    },
    methods: {
      search(){
        this.getUserList()
      },
      clearForm(){

        if(this.$refs['formInline']){
          this.$refs['formInline'].resetFields()
        }
        this.getUserList()
      },
      //查询岗位列表
      getPostSelectList() {
        this.$axios.getPostSelectList().then(res => {
          if (res.code === 0) {
            this.postOptions = res.data;
          }
        });
      },
      //查询角色列表
      getRoleSelectList() {
        this.$axios.getRoleSelectList().then(res => {
          if (res.code === 0) {
            this.roleOptions = res.data;
          }
        });
      },
      getDeptTreeList(){
        this.$axios.getDeptTreeList({status:0}).then(res=>{
          if (res.code === 0) {
            this.deptOptions=res.data;
            console.log("deptOptions"+this.deptOptions);
          }

        }).catch(err=>{
          console.log("deptOptions",err);
        })
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.formInline.deptId = data.id;
        this.getUserList();
      },
      getUserList(){
        this.loading = true;
        this.$axios.getUserList(this.formInline).then(res=>{
          this.loading=false
          if (res.code === 0) {
            this.userData=res.data.list;
            this.pageInfo.total=res.data.totalCount
          }

        }).catch(err=>{
          this.loading=false
          console.log("getUserListErr",err);
        })
      },
      // 选择复选框事件
      selectChange(val) {
        alert(val)
        this.selectData = val
        console.log('selectData',this.selectData)
      },
      editType(index,row){
        this.userForm.userId=row.userId
        this.userForm.status=row.status==0?'1':'0'
        this.$axios.editStatus(this.userForm).then(res=>{
          if (res.code===0) {
            this.getUserList()
            this.$message({
              type: 'success',
              message: '设置成功！'
            })
          }
        }).catch(err=>{
          console.log('editTypeErr',err)
        })

      },
      editUser(index,row){
        this.userFormVisible = true
        this.title="编辑用户"
        this.userForm.userId=row.userId
        this.userForm.deptId=row.deptId
        this.userForm.loginName=row.loginName
        this.userForm.status=row.status
        this.userForm.userName=row.userName
        this.userForm.sex=row.sex
        this.userForm.mobile=row.mobile
        this.userForm.email=row.email
        this.userForm.address=row.address
        this.userForm.birthday=row.birthday
        this.userForm.idCard=row.idCard
        this.userForm.avatar=row.avatar
        this.getPostSelectList()
        this. getRoleSelectList()
        // 回显岗位和角色
        this.$axios.getUserPostsAndUserRoles({userId:row.userId}).then(res=>{
          if (res.code===0) {
            this.userForm.postIds=res.data.postIds
            this.userForm.roleIds=res.data.roleIds
          }
        }).catch(err=>{
          console.log('getUserPostsAndUserRolesErr',err)
        })
      },
      deleteUser(index,row){
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.deleteUser({id:this.userForm.userId}).then(res=>{
            if (res.code===0) {
              this.getUserList()
              this.$message({
                type: 'success',
                message: '删除成功！'
              })
            }
          }).catch(err=>{
              console.log('deleteUserErr',err)
          })
        })
      },
      resetPassword(index,row){
        this.$prompt('请输入密码', '修改密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType:'password',
          inputPattern: /^\d{6,}$/,
          inputErrorMessage: '密码最少6位数'
        }).then(({ value }) => {
          this.$axios.editPassword({userId:row.userId,userPassword:value}).then(res=>{
            if (res.code===0) {
              this.getUserList()
              this.$message({
                type: 'success',
                message: '修改密码成功！'
              })
            }
          }).catch(err=>{
            console.log('resetPasswordErr',err)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.pageSize = parm.pageSize
        this.getUserList(this.formInline)
      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog == 'edit') {
          this.userFormVisible = false
        }
      },
      addUser(){
        this.userFormVisible = true
        this.title='添加用户'
        this.userForm.userId=''
        this.userForm.loginName=''
        this.userForm.deptId=null
        this.userForm.status=''
        this.userForm.userName=''
        this.userForm.sex=''
        this.userForm.mobile=''
        this.userForm.email=''
        this.userForm.address=''
        this.userForm.birthday=''
        this.userForm.idCard=''
        this.userForm.avatar=''

        if(this.$refs['userForm']){
          this.$refs['userForm'].resetFields()
        }
        if(this.formInline.deptId){
          this.userForm.deptId=this.formInline.deptId
        }
       // this.getDeptTreeList();
        this.getPostSelectList()
       this. getRoleSelectList()
      },
      submitForm(userForm){
        this.$refs[userForm].validate(valid => {

          if (valid) {
            this.loading = true
            // 请求方法
            if(this.userForm.userId){
               this.$axios.updateUser(this.userForm).then(res=>{
                 this.loading = false
                 if (res.code===0) {
                   this.userFormVisible = false
                   this.getUserList()
                   this.$message({
                     type: 'success',
                     message: '修改成功！'
                   })
                 }
               }).catch(err=>{
                 console.log('updateUserErr',err);
                 this.loading = false
               })
            }else{
              this.$axios.saveUser(this.userForm).then(res => {
                  this.loading = false
                  if (res.code===0) {
                    this.userFormVisible = false
                    this.getUserList()
                    this.$message({
                      type: 'success',
                      message: '保存成功！'
                    })
                  }
                }).catch(err=>{
                  console.log('saveUserErr',err);
                  this.loading = false
              })


            }
          } else {
            return false
          }
        })
      }
    }
  }
</script>

<style scoped>
 /* .user-search {
    margin-top: 20px;
  }*/
</style>


